package com.usian.wemedia.service.Impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.client.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.constants.message.WmNewsMessageConstants;
import com.usian.common.constants.wemedia.WemediaContans;
import com.usian.common.message.NewsAutoScanConstants;
import com.usian.model.admin.dtos.NewsAuthDto;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.model.media.vos.WmNewsVo;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmNewsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
;
import java.util.stream.Collectors;

@Service
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${fdfs.url}")
    String fileServerUrl;
    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    WmMaterialMapper materialMapper;
    @Autowired
    WmNewsMapper wmNewsMapper;

    @Override
    public ResponseResult findall(WmNewsPageReqDto dto) {
        //1.参数检查
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NULL_CANSHU);
        }

        //2.分页条件查询
        IPage pageParam = new Page(dto.getPage(),dto.getSize());

        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper();
        //状态精确查询
        if(dto.getStatus() != null){
            lambdaQueryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //频道精确查询
        if(null != dto.getChannelId()){
            lambdaQueryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }

        //时间范围查询
        if(dto.getBeginPubDate()!=null && dto.getEndPubDate()!=null){
            lambdaQueryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }

        //关键字模糊查询
        if(null != dto.getKeyword()){
            lambdaQueryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }

        //查询当前登录用户的信息
        Integer userId = WmThreadLocalUtils.getUserId();
        if(userId==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN,"没有获取到当前用户的ID");
        }
        lambdaQueryWrapper.eq(WmNews::getUserId,userId);

        //按照创建日期倒序
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        IPage pageResult = page(pageParam, lambdaQueryWrapper);

        //3.结果封装返回
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)pageResult.getTotal());
        responseResult.setData(pageResult.getRecords());
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }


    @Autowired
    private KafkaTemplate kafkaTemplate;
    /**
     * 修改和新增调的都是这个接口
     *
     * @param wmNews
     * @param isSubmit 是否为提交 1 为提交 0为草稿
     * @return
     */
    @Override
    @Transactional
    public void saveNews(WmNews wmNews, Short isSubmit) {
        wmNews.setStatus(isSubmit);
        wmNews.setUserId(WmThreadLocalUtils.getUserId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);
        boolean flag = false;
        if (wmNews.getId() == null) {
            flag = save(wmNews);
        } else {
            //如果是修改，则先删除素材与文章的关系
            LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(WmNewsMaterial::getNewsId, wmNews.getId());
            wmNewsMaterialMapper.delete(queryWrapper);
            flag = updateById(wmNews);
        }
        //发送消息
        if(flag){
            kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC,JSON.toJSONString(wmNews.getId()));
        }
    }
//    public ResponseResult saveNews(WmNewsDto wmNews, Short isSubmit) {
//        if (wmNews == null || wmNews.getContent().isEmpty()){
//         return  ResponseResult.errorResult(AppHttpCodeEnum.NULL_CANSHU);
//        }
//        WmNews news = new WmNews();
//        //将前端传过来的内容赋值到要保存到表里的对象
//        BeanUtils.copyProperties(wmNews, news);
//        if (WemediaContans.WM_NEWS_TYPE_AUTO.equals(wmNews.getType())) {
//            news.setType(null);
//        }
//        if (wmNews.getImages() != null && wmNews.getImages().size() != 0) {
//            StringBuffer buffer = new StringBuffer();
//            wmNews.getImages().forEach(s -> buffer.append(s.replace(fileServerUrl,"")).append(","));
//            news.setImages(buffer.toString().substring(0, buffer.toString().length() - 1));
//        }
//        news.setStatus(isSubmit);
//        Integer userId = WmThreadLocalUtils.getUserId();
//        news.setUserId(userId);
//        news.setCreatedTime(new Date());
//        news.setSubmitedTime(new Date());
//        news.setEnable((short) 1);
//        //对象字段赋值完成后，还有两件事1，确定素材和新闻的关系 2，保存新闻
//        if (news.getId() == null) {//以前没有这个文章，新增文章
//            save(news);
//        } else {//有id说明是修改文章
//            //删除关系表中新闻和素材的关系数据。
//            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, news.getId()));
//            //更新修改的内容
//            updateById(news);
//        }
//        //将前端传过来的新闻内容中的资源提取出来保存到集合中
//        String content = wmNews.getContent();
//        List<String> materialList = new ArrayList<>();
//        List<String> images = wmNews.getImages();
//        String url = images.get(0);
//        String b=url;
//        String[] split = url.split("192.168.58.138/");
//        String s = split[1];
//        if (b.equals(split[1])){
//            return ResponseResult.errorResult(AppHttpCodeEnum.NULL_CANSHU,"没替换掉");
//        }
//        materialList.add(s);
////        JSONArray array = JSON.parseArray(content);
////        array.forEach(m -> {
////            JSONObject object = JSON.parseObject(m.toString());
////            if (object.get("type").equals(WemediaContans.WM_NEWS_TYPE_IMAGE)) {
////                materialList.add(object.get("value").toString().replace(fileServerUrl, ""));
////            }
////        });
//
//        if (isSubmit == WmNews.Status.SUBMIT.getCode()) {
//            if (materialList.size() != 0) {//保存新闻内容中素材和新闻的关系
//                ResponseResult responseResult = saveRelativeInfoForContent(materialList, news.getId());
//                if (responseResult != null) {
//                    return responseResult;
//                }
//            }
//            //保存封面资源和新闻的关系数据
//            ResponseResult responseResult = saveRelativeInfoForCover(wmNews, materialList, news);
//            if (responseResult != null) {
//                return responseResult;
//            }
//        }
//        return null;
//    }

    @Override
    public ResponseResult wmNewsService(Integer id) {
        //1.参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }
        //2.查询数据
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }

        //3.结果返回
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public ResponseResult delbyid(Integer id) {
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //判断是否发表
        if (wmNews.getStatus() ==9 && wmNews.getEnable() ==1){
            return ResponseResult.errorResult(AppHttpCodeEnum.NULL_CANSHU,"文章已发布不能删除");
        }
        //去除图片/视频(素材)关联
        QueryWrapper<WmNewsMaterial> wmMaterialQueryWrapper = new QueryWrapper<>();
        wmMaterialQueryWrapper.eq("news_id",id);
        wmNewsMaterialMapper.delete(wmMaterialQueryWrapper);
        //删除
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 文章上下架
      * @param dto
     * @return
     */
    @Override
    public ResponseResult donworup(WmNewsDto dto) {
        //检查参数
        if (dto.getId() == null && dto.getEnable() ==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.NULL_CANSHU);
        }
        //查询文章信息
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.NULL_CANSHU,"文章不存在");
        }
        //判断文章状态是否发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return  ResponseResult.errorResult(AppHttpCodeEnum.NULL_CANSHU,"文章未发布,不能上架");
        }
        //4.修改文章状态，同步到app端（后期做）TODO
        if(dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){
            if(wmNews.getArticleId()!=null) {
                Map<String, Object> mesMap = new HashMap<>();
                mesMap.put("enable", dto.getEnable());
                mesMap.put("articleId", wmNews.getArticleId());
                kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(mesMap));
            }
            update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询所有待发布or定时发布的文章id
     * @return
     */
    @Override
    public List<Integer> findRelease() {
        //查询所有人工审核通过的文章id
        List<WmNews> list1 = list(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getStatus, 4).lt(WmNews::getPublishTime,new Date()));
        //查询所有定时发布的文章的id
        List<WmNews> list = list(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getStatus, 8).lt(WmNews::getPublishTime,new Date()));
        for (WmNews wmNews : list1) {
            list.add(wmNews);
        }
        List<Integer> resultList = list.stream().map(WmNews::getId).collect(Collectors.toList());
        return resultList;
    }

    //查询文章列表
    @Override
    public PageResponseResult findListAndPage(NewsAuthDto dto) {
        //检查参数
        if (dto== null){
            return (PageResponseResult) ResponseResult.errorResult(AppHttpCodeEnum.NULL_CANSHU);
        }
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());
        dto.setTitle("%"+dto.getTitle()+"%");

        //2.分页查询
        List<WmNewsVo> list = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        int count = wmNewsMapper.findListCount(dto);
        //返回数据
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), count);
        responseResult.setData(list);
        return responseResult;
    }

    @Autowired
    WmUserMapper wmUserMapper;

    /**
     * 通过文章ID查文章
     * @param id
     * @return
     */
    @Override
    public WmNewsVo findWmNewsVo(Integer id) {
        //通过id查询文章详情
        WmNews wmNews = getById(id);
        WmUser wmUser = null;
        if (wmNews != null && wmNews.getUserId() != null){
            //通过用户id查找用户信息
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }
        WmNewsVo wmNewsVo = new WmNewsVo();
        //数据封装
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if (wmUser !=null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        return wmNewsVo;
    }

    /**
     * 保存封面资源和新闻的关系数据
     *
     * @param wmNews       前端传过来的新闻对象
     * @param materialList 包含所有详情内容资源路劲的集合
     * @param news         要更新或保存到表里的新闻对象
     * @return
     */
    private ResponseResult saveRelativeInfoForCover(WmNewsDto wmNews, List<String> materialList, WmNews news) {
        //前端传过来的封面图集合
        List<String> images = wmNews.getImages();
        //如果前端再提交数据时，封面选择的是自动
        if (wmNews.getType() == WemediaContans.WM_NEWS_TYPE_AUTO) {
            if (materialList.size() == 0) {//无图模式
                news.setType(WemediaContans.WM_NEWS_NONE_IMAGE);
            } else if (materialList.size() <= 2) {//单图模式
                news.setType(WemediaContans.WM_NEWS_SINGLE_IMAGE);
                if (images == null) images = new ArrayList<>();
                images.clear();
                images.add(materialList.get(0));
            } else {//多图模式
                news.setType(WemediaContans.WM_NEWS_MANY_IMAGE);
                images = materialList.stream().limit(3).collect(Collectors.toList());
            }
            //更新已保存的新闻表中封面图的数据
            if (images.size() != 0)
                news.setImages(images.toString().replace("[", "")
                        .replace("]", "").replace(fileServerUrl, "")
                        .replace(" ", ""));
            updateById(news);
        }
        if (images != null && images.size() > 0) {
            images = images.stream().map(i->i.replace(fileServerUrl,"")).collect(Collectors.toList());
            ResponseResult responseResult = saveRelativeInfo(images, news.getId(),WemediaContans.WM_COVER_REFERENCE);
            if (responseResult != null) {
                return responseResult;
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存新闻内容中素材和新闻的关系
     *
     * @param materialList
     * @param id
     * @return
     */
    private ResponseResult saveRelativeInfoForContent(List<String> materialList, Integer id) {
        return saveRelativeInfo(materialList, id, WemediaContans.WM_CONTENT_REFERENCE);
    }

    /**
     * 具体执行中间关系表的数据插入
     *
     * @param materialList       内容中引用的资源路劲集合
     * @param id                 新闻id
     * @param wmContentReference 引用类型，当前是内容引用
     * @return
     */
    private ResponseResult saveRelativeInfo(List<String> materialList, Integer id, Short wmContentReference) {
        List<WmMaterial> list = materialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materialList));
        if (list == null || list.size() == 0) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "资源错误");
        List<String> idList = new ArrayList<>();
        list.forEach(l -> idList.add(l.getId().toString()));
        wmNewsMaterialMapper.saveRelationsByContent(idList, id, wmContentReference);
        return null;
    }


}
